<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="800px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #permissions="{ model, field }" >
        <CheckboxGroup
          name="permissions"
          :value="model[field]"
          v-model:value="model[field]"
        >
          <div>
            <br/>
            <div v-for="item in permissionModules" :key="item.name" style="margin-top: 20px;">
              <h4>{{ item.name }}</h4>
              <Checkbox v-for="i in item.permissions" :value="i.code">{{ i.name }}</Checkbox>
            </div>
          </div>
        </CheckboxGroup>
      </template>
    </BasicForm>

  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { CheckboxGroup, Checkbox } from 'ant-design-vue'
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { createRole, editRole, getPermissionModuleList } from '@/api/role'

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(false);
  const id = ref();
  const permissionModules = ref([]);

  const schemas: FormSchema[] = [
    {
      field: 'name',
      label: '名称',
      component: 'Input',
      required: true,
    },
    {
      field: 'permissions',
      label: '权限',
      component: 'Input',
      required: true,
      slot: 'permissions',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: schemas,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    const res = await getPermissionModuleList();
    permissionModules.value = res.items;
    console.log(permissionModules.value[0].permissions);
    
    isUpdate.value = data?.isUpdate;
    id.value = data?.record?.id;
    resetFields();
    setDrawerProps({ confirmLoading: false });
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        await editRole(id.value, values);
      } else {
        await createRole(values);
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>